package com.zhouyu.exampleboot.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhouyu.exampleboot.entity.Child;
import com.zhouyu.exampleboot.entity.UserPoi;
import com.zhouyu.exampleboot.entity.Wife;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * Description:
 * json字段提取工具
 *
 * @author zhouyu
 * @date 2021/9/15 11:44
 */
public class JsonExtraUtil {
    public String getJson() {
        JSONObject jsonObject = new JSONObject();
        UserPoi userPoi = new UserPoi();
        userPoi.setAge(29);
        userPoi.setClassId(1);
        userPoi.setName("zhouyu");
        Wife wife = new Wife();
        wife.setId("1");
        wife.setAge("28");
        wife.setName("szq");
        userPoi.setWife(wife);
        Child child = new Child();
        child.setHabit("打球");
        child.setName("思齐");
        child.setAge(2);

        Child child2 = new Child();
        child2.setHabit("画画");
        child2.setName("乐知");
        child2.setAge(3);

        ArrayList<Child> children = new ArrayList<>();
        children.add(child);
        children.add(child2);
        userPoi.setChilds(children);

        jsonObject.put("errcode", 0);
        jsonObject.put("user", userPoi);
        return jsonObject.toJSONString();
    }

    public LinkedList<String> getLayeres() {
        LinkedList<String> treeSets = new LinkedList<>();
        treeSets.add("user");
        treeSets.add("wife");
        return treeSets;
    }

    public Object getInfo(Class clazz) {
        String json = getJson();
        Object value = JSONObject.parseObject(json);
        LinkedList<String> layeres = getLayeres();
        int index = 0;
        while (true) {
            if (index == layeres.size()) {
                // 已经遍历到最后一层
                value = JSONObject.toJavaObject((JSON) value, clazz);
                break;
            }

            if (value instanceof JSONObject) {
                //层层解析jsonObj
                JSONObject jsonObject = (JSONObject) value;
                String key = layeres.get(index);
                value = jsonObject.get(key);
                index++;
            }
            if (value instanceof JSONArray) {
                //解析到数组，直接返回
                JSONArray jsonArray = (JSONArray) value;
                value = jsonArray.toJavaList(clazz);
                break;
            }
        }
        return value;
    }

}
